import React, { useEffect, useState } from 'react';
import { getUmePic, isEmpty } from '@/utils/common';
import { Message, Picture, Price, ModalWrap } from '@/design';
import { useDispatch, useSelector } from 'umi';
import NumberPicker from '@/components/NumberPicker/NumberPicker';
import styles from './specPicker.less';

export default function (props: any) {
  const dispatch = useDispatch();
  //购物车
  const { cartList } = useSelector((state:any) => state.cartList);
  
  const [state, setState] = useState({
    chooseSkuMap: new Map(),
    chooseTasteCategoryIdMap: new Map(),//這個主要是為了多規格的時候加的 判斷當前選的規格是否有选
    chooseTasteCategoryIdLength: 1 //每个规格下的选的份数
  });

  useEffect(() => {
    setState({ ...state, chooseSkuMap: new Map(), chooseTasteCategoryIdMap: new Map(), chooseTasteCategoryIdLength: 1 });
  }, [props.specVisiable])

 
  /* 選擇規格 */
  const selectAttr = (parentSpec: ITasteCategoryListProps, curSpec: tasteItemListProps) => {
    const { isChooseMulti, tasteNumber, categoryName } = parentSpec;
    let newChooseTasteCategoryIdMap = state.chooseTasteCategoryIdMap;
    let length:number = state.chooseTasteCategoryIdLength;
    const { braId, createTime, formatCreateTime, price, tasteCategoryId, tasteItemId, tasteName, tasteItemNumber, tasteId } = curSpec;
    let newChooseSkuMap = state.chooseSkuMap;
    let setJson = {
      braId,
      createTime,
      formatCreateTime,
      price,
      tasteCategoryId,
      tasteItemId,
      tasteName,
      tasteId,
      tasteItemNumber,
      num: 1
    };//要设置进tasteList的object，主要是为了给后端
    if(isChooseMulti) { //多选的
      if(newChooseTasteCategoryIdMap.has(tasteCategoryId) && !newChooseSkuMap.has(curSpec.tasteItemId) && length >= tasteNumber ) {
        return Message.error(`『${categoryName}』最多可選擇 ${tasteNumber} 份`)
      }
      if(newChooseSkuMap.has(curSpec.tasteItemId)) {//按照单个tasteItem
        newChooseSkuMap.delete(curSpec.tasteItemId);
      } else {
        newChooseSkuMap = newChooseSkuMap.set(curSpec.tasteItemId, setJson)
      }
      //当前规格下份数
      if(newChooseTasteCategoryIdMap.has(tasteCategoryId)) {
        if(!newChooseSkuMap.has(curSpec.tasteItemId)) {
          length = length - 1
        } else {
          length = length + 1
        }
      } else {
        length = 1
      }
      newChooseTasteCategoryIdMap.set(curSpec.tasteCategoryId, setJson)
    } else {//单选
      if(state.chooseSkuMap.get(tasteCategoryId)?.tasteItemId === tasteItemId) {
        newChooseSkuMap.delete(tasteCategoryId)
      } else {
        newChooseSkuMap = newChooseSkuMap.set(tasteCategoryId, setJson)
      }
    }
    setState({ 
      ...state,
      chooseSkuMap: newChooseSkuMap,
      chooseTasteCategoryIdMap: newChooseTasteCategoryIdMap,
      chooseTasteCategoryIdLength: length
     });
  }

  const handleNumChange = (num: number, curSpec: tasteItemListProps) => {
    let newChooseSkuMap = state.chooseSkuMap;
    const { braId, createTime, formatCreateTime, price, tasteCategoryId, tasteItemId, tasteName, tasteItemNumber } = curSpec
    let setJson = {
      braId,
      createTime,
      formatCreateTime,
      price,
      tasteCategoryId,
      tasteItemId,
      tasteName,
      tasteItemNumber,
      num
    }
    if(newChooseSkuMap.has(curSpec.tasteItemId)){
      if(num === 0) {//返回的是0 则删除
        newChooseSkuMap.delete(curSpec.tasteItemId)
      } else {
        newChooseSkuMap.set(curSpec.tasteItemId, setJson)
      }
    }
    setState({ ...state, chooseSkuMap: newChooseSkuMap });
  }

  //激活class
  const activeClassName = (spec: ITasteCategoryListProps, attr: tasteItemListProps) => {
    let res = '';
    if(spec.isChooseMulti) {
      res =  state.chooseSkuMap.get(attr.tasteItemId) ? styles.active : ''
    } else {
      res = state.chooseSkuMap.get(attr.tasteCategoryId)?.tasteItemId === attr.tasteItemId ? styles.active : ''
    }
    return res;
  }

  //將单个商品的數據整合成key value productId ===> 數組
  const mapTasteCategoryList = (array: any) => {
    return array.reduce((m:any, n:any) => {
      if(n.isChoose === 1) {
        if (!m[n.tasteCategoryId]) {
          m[n.tasteCategoryId] = {list: []}
        } 
        m[n.tasteCategoryId].list.push({
          categoryName: n.categoryName,
          tasteItemList: n.tasteItemList
        })
        return m
      } 
      return {}
    }, {})
  }

  /* 所选的菜品tasteItemIds */
  const chooseTasteIds = (tasteList: any, param: string) => {
    let str:any = [];
    tasteList.forEach((o:any)=> {
      str.push(`${o[param]}`)
    })
    return str.join('_')
  }

  //點擊確定做處理
  const handleSubmit = () => {
    const { onClose, goodsDetail, onClickSure } = props;
    let tasteCategoryListObj = mapTasteCategoryList(goodsDetail.tasteCategoryList);//需要必选的规格
    console.log('要必選的規格', tasteCategoryListObj)
    let chooseArray:any = [...state.chooseSkuMap.values()]; //當親選取的規格
    let chooseIds = [...new Set(chooseArray.map((item:any)=>item.tasteCategoryId))] //當前選取的Ids
    if(!isEmpty(tasteCategoryListObj)) {//必选项时做下拦截
      let requestIds = Object.keys(tasteCategoryListObj) //必選Ids
      if(chooseIds.length !== requestIds.length) {
        let notChooseIds= [];//找出必選當中沒有選擇的Id
        notChooseIds = requestIds.filter(item=>{
            return chooseIds.indexOf(item) === -1
        });
        for(let i = 0; i < notChooseIds.length; i++) {
          let name = tasteCategoryListObj[notChooseIds[i]].list[0].categoryName
          return Message.error(`請選擇${name}`);
        }
      }
    }
    
    const { productPrice, productIcon1, productId, categoryId, productName } = goodsDetail
    if(onClickSure) {
      if(isEmpty([...state.chooseSkuMap.values()])) {
        return Message.error('请选择')
      }
      return onClickSure([...state.chooseSkuMap.values()])
    }
    let good = {
      tasteList: [...state.chooseSkuMap.values()],
      categoryId,
      productIcon: productIcon1,
      productId,
      productName,
      productPrice,
      productQuantity: 1
    } 
    
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let tempMap = new Map();
    
    newCartList.forEach((item: any)=>{
      let tasteItemIds = chooseTasteIds(item.tasteList, 'tasteItemId');
      let tasteNums = chooseTasteIds(item.tasteList, 'num')
      tempMap.set(`${item.productId}_${tasteItemIds}_${tasteNums}`, item)
    })
    let curTasteNums = ([...state.chooseSkuMap.values()].map((item:any) => item.num)).join('_');
    let curTasteItemIds = ([...state.chooseSkuMap.values()].map((item:any) => item.tasteItemId)).join('_')
    if(tempMap.has(`${productId}_${curTasteItemIds}_${curTasteNums}`)) {
      tempMap.set(`${productId}_${curTasteItemIds}_${curTasteNums}`, {
        ...good,
        productQuantity: tempMap.get(`${productId}_${curTasteItemIds}_${curTasteNums}`).productQuantity + 1
      })
    } else {
      tempMap.set(`${productId}_${curTasteItemIds}_${curTasteNums}`, good)
    }
    newCartList = [...tempMap.values()];
    console.log('yaojinq', newCartList)
    // return
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })
    onClose && onClose();
  }
  const { goodsDetail: { tasteCategoryList }, goodsDetail, specVisiable } = props;
  
  //商品的圖片、價格
  const getGoodHead = () => {
    return (<div className={styles.spec_head}>
      <Picture className={styles.pic} src={getUmePic(goodsDetail.productIcon1)} />
      <div>
        <h3 className={styles.productName}>
          {goodsDetail.productName}
          {/* <Price price={goodsDetail.websitePrice} /> */}
        </h3>
        <p className={styles.selected}>月售 {goodsDetail.monthSaleAmount}</p>
        <h3 className={styles.price}>
          <Price price={goodsDetail.productPrice} />
        </h3>
     </div>
     </div>)
  }

  return (<ModalWrap modalVisiable={specVisiable} onClose={props.onClose} showPic picNode={getGoodHead()} onClickSure={handleSubmit}>
  {!isEmpty(tasteCategoryList) && tasteCategoryList.map((spec:ITasteCategoryListProps, index:number) => <div key={spec.tasteCategoryId}>
   <label className={styles.label}>{spec.categoryName}</label>
   <ul className={styles.spec_list}>
     {spec.tasteItemList.map((attr:tasteItemListProps, sIndex:number) => {
       const showBadge = !!(state.chooseSkuMap.get(attr.tasteItemId)?.tasteItemNumber > 1)
       return(
         <li
           key={attr.tasteItemId}
           onClick={()=>{selectAttr(spec, attr)}}
           className={activeClassName(spec, attr)}
         >
           <span className={styles.tasteName}>{attr.tasteName}</span>
           <span className={styles.spec_price}>
             NT${attr.price}
           </span>
           {state.chooseSkuMap.get(attr.tasteItemId)?.tasteItemNumber > 1 && <span><NumberPicker value={state.chooseSkuMap.get(attr.tasteItemId)?.num} onChange={handleNumChange} attr={attr} max={state.chooseSkuMap.get(attr.tasteItemId)?.tasteItemNumber} hideNumber/></span>}
           {/* 可选的大于1才显示 */}
           {showBadge ? <span className={styles.badge}>{state.chooseSkuMap.get(attr.tasteItemId)?.num}</span> : null}
         </li>
       )
     })}
   </ul>
 </div>)}
</ModalWrap>)
}